package com.jsmile.cloud.tradecenter.cart;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Lists;
import com.jsmile.cloud.goodscenter.api.feign.SkuServiceApi;
import com.jsmile.cloud.goodscenter.api.req.spu.ReqSkuCheck;
import com.jsmile.cloud.goodscenter.api.res.ResSku;
import com.jsmile.cloud.tradecenter.api.exception.TradeException;
import com.jsmile.cloud.tradecenter.api.req.cart.ReqAddCart;
import com.jsmile.cloud.tradecenter.api.req.cart.ReqCartDetial;
import com.jsmile.cloud.tradecenter.api.req.cart.ReqDeleteCart;
import com.jsmile.cloud.tradecenter.api.req.cart.ReqUpdateCart;
import com.jsmile.cloud.tradecenter.cart.model.ShoppingCart;
import com.jsmile.cloud.tradecenter.cart.repo.ShoppingCartRepository;
import com.jsmile.mall.api.JSmileResult;
import com.jsmile.mall.cache.kit.SpringKit;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class CartApplicationService {

    private final ShoppingCartRepository shoppingCartRepository;

    public Boolean addCart(ReqAddCart reqAddCart) {
        ShoppingCart cart = ShoppingCart.addCart(reqAddCart);
        JSmileResult<List<ResSku>> jSmileResult =
            SpringKit.getBean(SkuServiceApi.class).skuCheck(ReqSkuCheck.builder().hasCheck(true).skuList(Lists.newArrayList(cart.createSkuCheck())).build());
        if (jSmileResult.getResSuccess()) {
            Map<Long, ResSku> skuMap = jSmileResult.getResData().stream().collect(Collectors.toMap(ResSku::getSkuId, a -> a, (k1, k2) -> k1));
            cart.setJoinPrice(skuMap.get(cart.getSkuId()).getSellingPrice());
        } else {
            throw new TradeException(jSmileResult.getResCode(), jSmileResult.getResMsg(), null);
        }
        log.info("添加购物车:{]", cart);
        return shoppingCartRepository.saveOrUpdate(cart);
    }

    @Transactional(readOnly = false)
    public Boolean updateCart(ReqUpdateCart reqUpdateCart) {
        log.info("更新购物车:{]", reqUpdateCart);
        ShoppingCart cart = ShoppingCart.updateCart(reqUpdateCart);
        JSmileResult<List<ResSku>> jSmileResult =
            SpringKit.getBean(SkuServiceApi.class).skuCheck(ReqSkuCheck.builder().hasCheck(true).skuList(Lists.newArrayList(cart.createSkuCheck())).build());
        if (jSmileResult.getResSuccess()) {
            Map<Long, ResSku> skuMap = jSmileResult.getResData().stream().collect(Collectors.toMap(ResSku::getSkuId, a -> a, (k1, k2) -> k1));
            cart.setJoinPrice(skuMap.get(cart.getSkuId()).getSellingPrice());
        } else {
            throw new TradeException(jSmileResult.getResCode(), jSmileResult.getResMsg(), null);
        }
        shoppingCartRepository.removeById(reqUpdateCart.getOldCartId());
        return shoppingCartRepository.saveOrUpdate(cart);
    }

    public Boolean deleteCart(ReqDeleteCart reqDeleteCart) {
        log.info("删除购物车:{]", reqDeleteCart);
        return shoppingCartRepository.removeByIds(reqDeleteCart.getCartIds());
    }

    public Boolean deleteCart(Long userId, List<Long> skuIds) {
        return shoppingCartRepository.remove(new UpdateWrapper<ShoppingCart>().lambda().eq(ShoppingCart::getUserId, userId).in(ShoppingCart::getSkuId, skuIds));
    }

    public Boolean clearCart(ReqCartDetial reqCartDetial) {
        log.info("清空购物车:{]", reqCartDetial);
        return shoppingCartRepository.remove(new UpdateWrapper<ShoppingCart>().lambda().eq(ShoppingCart::getUserId, reqCartDetial.getCurUserId()));
    }

    public long countCart(ReqCartDetial reqCartDetial) {
        log.info("购物车数量:{]", reqCartDetial);
        return shoppingCartRepository.count(new QueryWrapper<ShoppingCart>().lambda().eq(ShoppingCart::getUserId, reqCartDetial.getCurUserId()));
    }

    public List<ShoppingCart> cartDetial(ReqCartDetial reqCartDetial) {
        List<ShoppingCart> shoppingCarts = shoppingCartRepository.list(new QueryWrapper<ShoppingCart>().lambda().eq(ShoppingCart::getUserId, reqCartDetial.getCurUserId()));
        log.info("购物车详情:{]", reqCartDetial);
        return shoppingCarts;
    }
}
